package com.ruoyi.ldzlsb.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.ldzlsb.domain.SbInspectionPlan;
import com.ruoyi.ldzlsb.domain.SbInspectionRecord;
import com.ruoyi.ldzlsb.service.ISbInspectionPlanService;
import com.ruoyi.ldzlsb.service.ISbInspectionCycleConfigService;
import com.ruoyi.ldzlsb.domain.SbInspectionCycleConfig;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.ldzlsb.service.ISbInspectionRecordService;
import com.ruoyi.ldzlsb.domain.SbEquipment;
import com.ruoyi.ldzlsb.service.ISbEquipmentService;
import com.ruoyi.ldzlsb.domain.SbInspectionConfig;
import com.ruoyi.ldzlsb.service.ISbInspectionConfigService;
import com.ruoyi.ldzlsb.domain.SbInspectionItem;
import com.ruoyi.ldzlsb.service.ISbInspectionItemService;
import java.util.ArrayList;
import com.ruoyi.ldzlsb.domain.vo.SbEquipmentVo;
import java.util.Map;
import java.util.HashMap;

/**
 * 巡检计划Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/inspection/plan")
public class SbInspectionPlanController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(SbInspectionPlanController.class);
    
    @Autowired
    private ISbInspectionPlanService sbInspectionPlanService;
    
    @Autowired
    private ISbInspectionCycleConfigService sbInspectionCycleConfigService;

    @Autowired
    private ISbInspectionRecordService sbInspectionRecordService;

    @Autowired
    private ISbEquipmentService sbEquipmentService;

    @Autowired
    private ISbInspectionConfigService sbInspectionConfigService;

    @Autowired
    private ISbInspectionItemService sbInspectionItemService;

    /**
     * 查询巡检计划列表
     */
    //@RequiresPermissions("sb:plan:list")
    @GetMapping("/list")
    public TableDataInfo list(SbInspectionPlan sbInspectionPlan)
    {
        startPage();
        List<SbInspectionPlan> list = sbInspectionPlanService.selectSbInspectionPlanList(sbInspectionPlan);
        return getDataTable(list);
    }

    /**
     * 导出巡检计划列表
     */
    //@RequiresPermissions("sb:plan:export")
    @Log(title = "巡检计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SbInspectionPlan sbInspectionPlan)
    {
        List<SbInspectionPlan> list = sbInspectionPlanService.selectSbInspectionPlanList(sbInspectionPlan);
        ExcelUtil<SbInspectionPlan> util = new ExcelUtil<SbInspectionPlan>(SbInspectionPlan.class);
        util.exportExcel(response, list, "巡检计划数据");
    }

    /**
     * 获取巡检计划详细信息
     */
    //@RequiresPermissions("sb:plan:query")
    @GetMapping(value = "/{planId}")
    public AjaxResult getInfo(@PathVariable("planId") Long planId)
    {
        SbInspectionPlan plan = sbInspectionPlanService.selectSbInspectionPlanByPlanId(planId);
        
        // 获取周期配置信息
        if (plan != null) {
            SbInspectionCycleConfig cycleConfig = sbInspectionCycleConfigService.selectSbInspectionCycleConfigByPlanId(planId);
            if (cycleConfig != null) {
                plan.setCycleConfigJson(cycleConfig.getConfigData());
            }
            
            // 获取设备信息
            if (plan.getEquipmentId() != null) {
                try {
                    // 查询设备信息
                    SbEquipmentVo equipment = sbEquipmentService.selectSbEquipmentByEquipmentId(plan.getEquipmentId());
                    if (equipment != null) {
                        // 创建设备列表并添加到响应数据中
                        Map<String, Object> resultMap = new HashMap<>();
                        resultMap.put("planInfo", plan);
                        
                        List<SbEquipmentVo> equipmentList = new ArrayList<>();
                        equipmentList.add(equipment);
                        resultMap.put("equipmentList", equipmentList);
                        
                        // 获取巡检项目信息
                        if (plan.getConfigId() != null) {
                            try {
                                // 查询巡检配置信息
                                SbInspectionConfig config = sbInspectionConfigService.selectSbInspectionConfigByConfigId(plan.getConfigId());
                                if (config != null) {
                                    // 查询巡检项目列表
                                    List<SbInspectionItem> items = sbInspectionItemService.selectSbInspectionItemByConfigId(plan.getConfigId());
                                    if (items != null && !items.isEmpty()) {
                                        resultMap.put("inspectionItems", items);
                                    }
                                }
                            } catch (Exception e) {
                                logger.error("获取巡检项目信息失败", e);
                            }
                        }
                        
                        // 获取巡检记录信息
                        try {
                            List<SbInspectionRecord> records = sbInspectionRecordService.selectSbInspectionRecordByPlanId(planId);
                            if (records != null && !records.isEmpty()) {
                                resultMap.put("inspectionRecords", records);
                            }
                        } catch (Exception e) {
                            logger.error("获取巡检记录信息失败", e);
                        }
                        
                        return AjaxResult.success(resultMap);
                    }
                } catch (Exception e) {
                    logger.error("获取设备信息失败", e);
                }
            }
        }
        
        return AjaxResult.success(plan);
    }

    /**
     * 新增巡检计划
     */
    //@RequiresPermissions("sb:plan:add")
    @Log(title = "巡检计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SbInspectionPlan sbInspectionPlan)
    {
        // 处理周期配置信息
        String cycleConfigJson = sbInspectionPlan.getCycleConfigJson();
        if (StringUtils.isNotEmpty(cycleConfigJson)) {
            sbInspectionPlan.setCycleValue(sbInspectionPlan.getCycleValue() != null ? sbInspectionPlan.getCycleValue() : 1);
        }
        
        int rows = sbInspectionPlanService.insertSbInspectionPlan(sbInspectionPlan);
        
        // 保存周期配置
        if (rows > 0 && StringUtils.isNotEmpty(cycleConfigJson)) {
            SbInspectionCycleConfig cycleConfig = new SbInspectionCycleConfig();
            cycleConfig.setPlanId(sbInspectionPlan.getPlanId());
            cycleConfig.setCycleType(sbInspectionPlan.getCycleType());
            cycleConfig.setCycleValue(sbInspectionPlan.getCycleValue());
            cycleConfig.setConfigData(cycleConfigJson);
            sbInspectionCycleConfigService.insertSbInspectionCycleConfig(cycleConfig);
        }
        
        return toAjax(rows);
    }

    /**
     * 修改巡检计划
     */
    //@RequiresPermissions("sb:plan:edit")
    @Log(title = "巡检计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SbInspectionPlan sbInspectionPlan)
    {
        // 处理周期配置信息
        String cycleConfigJson = sbInspectionPlan.getCycleConfigJson();
        if (StringUtils.isNotEmpty(cycleConfigJson)) {
            sbInspectionPlan.setCycleValue(sbInspectionPlan.getCycleValue() != null ? sbInspectionPlan.getCycleValue() : 1);
        }
        
        int rows = sbInspectionPlanService.updateSbInspectionPlan(sbInspectionPlan);
        
        // 保存或更新周期配置
        if (rows > 0 && StringUtils.isNotEmpty(cycleConfigJson)) {
            SbInspectionCycleConfig cycleConfig = new SbInspectionCycleConfig();
            cycleConfig.setPlanId(sbInspectionPlan.getPlanId());
            cycleConfig.setCycleType(sbInspectionPlan.getCycleType());
            cycleConfig.setCycleValue(sbInspectionPlan.getCycleValue());
            cycleConfig.setConfigData(cycleConfigJson);
            sbInspectionCycleConfigService.saveOrUpdateCycleConfig(cycleConfig);
        }
        
        return toAjax(rows);
    }

    /**
     * 删除巡检计划
     */
    //@RequiresPermissions("sb:plan:remove")
    @Log(title = "巡检计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{planIds}")
    public AjaxResult remove(@PathVariable Long[] planIds)
    {
        return toAjax(sbInspectionPlanService.deleteSbInspectionPlanByPlanIds(planIds));
    }

    /**
     * 生成巡检单
     */
    //@RequiresPermissions("sb:plan:generate")
    @Log(title = "生成巡检单", businessType = BusinessType.INSERT)
    @PostMapping("/generate/{planId}")
    public AjaxResult generateRecord(@PathVariable("planId") Long planId)
    {
        try {
            // 通过计划ID获取计划信息
            SbInspectionPlan plan = sbInspectionPlanService.selectSbInspectionPlanByPlanId(planId);
            if (plan == null) {
                return AjaxResult.error("巡检计划不存在");
            }
            
            // 检查设备是否正在巡检中
            if (sbInspectionRecordService.checkEquipmentInInspection(plan.getEquipmentId())) {
                return AjaxResult.error("该设备正在巡检中，无法生成新的巡检单");
            }
            
            // 调用服务创建巡检单
            SbInspectionRecord record = sbInspectionPlanService.createInspectionRecordFromPlan(plan);
            if (record != null) {
                return AjaxResult.success("生成巡检单成功", record);
            } else {
                return AjaxResult.error("生成巡检单失败");
            }
        } catch (Exception e) {
            logger.error("生成巡检单失败", e);
            return AjaxResult.error("生成巡检单失败: " + e.getMessage());
        }
    }

    /**
     * 生成计划编号
     */
    @GetMapping("/generate/code")
    public AjaxResult generatePlanCode()
    {
        String planCode = sbInspectionPlanService.generatePlanCode();
        return AjaxResult.success(planCode);
    }

    /**
     * 检查计划编号唯一性
     */
    @GetMapping("/check/{planCode}")
    public AjaxResult checkPlanCodeUnique(@PathVariable("planCode") String planCode)
    {
        // 创建临时对象用于检查
        SbInspectionPlan plan = new SbInspectionPlan();
        plan.setPlanCode(planCode);
        return AjaxResult.success(sbInspectionPlanService.checkPlanCodeUnique(plan));
    }

    /**
     * 更新计划状态
     */
    //@RequiresPermissions("sb:plan:edit")
    @Log(title = "巡检计划状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status/{planId}/{status}")
    public AjaxResult updateStatus(@PathVariable("planId") Long planId, @PathVariable("status") String status)
    {
        SbInspectionPlan plan = new SbInspectionPlan();
        plan.setPlanId(planId);
        plan.setStatus(status);
        return toAjax(sbInspectionPlanService.updateSbInspectionPlan(plan));
    }
} 